package net.xdclass.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 具体来说，它使用了 @ServerEndpoint 注解来指定 WebSocket 端点的 URL，
 * 使用了 @OnOpen、@OnMessage、@OnClose 和 @OnError 注解来定义 WebSocket 事件处理器。
 * 要使用这个 WebSocket 服务端，我们需要部署它到一个支持 WebSocket 的 Web 容器中
 */
@Component
@Slf4j
@ServerEndpoint("/dcloud")
public class WebSocketController {

    /** 记录链接在线数量 **/
    private static final AtomicInteger onlineCount = new AtomicInteger(0);


    /** 存放每个客户端对应的 WebSocketServer 对象 **/
    private static CopyOnWriteArraySet<WebSocketController> webSocketSet = new CopyOnWriteArraySet<>();


    /** 与某个客户端的连接会话，需要通过它来给客户端发送数据 **/
    private Session session;


    /** 心跳报文 **/
    private static final String HEARTBEAT_PACKETS = "The heartbeat packets";

    @OnOpen
    public void onOpen(Session session) {
        this.session=session;
        webSocketSet.add(this);
        onlineCount.getAndIncrement();
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        if (HEARTBEAT_PACKETS.equals(message)){
            log.debug("[消息订阅] - 心跳.");
            return;
        }
        log.info("Received message: {}",message);
        session.getBasicRemote().sendText("Server received: " + message);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("Connection closed: {}",session.getId());
        webSocketSet.remove(this);
        onlineCount.getAndDecrement();
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("[历史数据回放] - WS 异常断开 {}",throwable.getMessage());
    }
    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) {
        for (WebSocketController item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                log.error("[NVR 数据对接] - 数据推送异常, 数据: [{}].", message, e);
                continue;
            }
        }
    }


    /**
     * 指定会话推送
     * @param message
     */
    public static void sendInfo(Session session, String message) {
        for (WebSocketController item : webSocketSet) {
            try {
                if (null != session && item.session.equals(session)) {
                    item.sendMessage(message);
                }

            } catch (IOException e) {
                log.error("[数据对接] - 数据推送异常, 数据: [{}].", message, e);
                continue;
            }
        }
    }

    /**
     * 向链接推送消息
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

}
